#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import json

from common.common import output_result_file
from common.const import AuthType
from common.parse_parafile import ParamFileUtil, get_env_variable
from generaldb.saphana.comm.common_util import log
from generaldb.saphana.comm.saphana_const import SaphanaConst, SaphanaJsonConstant, ListAppQueryConstant
from saphana.resource.saphana_cluster_manager import SaphanaClusterManage
from saphana.schemas.saphana_schemas import ListAppV2Response, Resource


class SaphanaResourceService:

    def __init__(self, pid, job_id, sub_job_id):
        self.pid = pid
        self.job_id = job_id
        self.sub_job_id = sub_job_id
        self._init_db_param(pid)
        self._saphana_cluster = SaphanaClusterManage({SaphanaJsonConstant.SYSTEM_ID: self.sid,
                                                      SaphanaJsonConstant.SYSTEM_DB_PORT: self.system_db_port,
                                                      SaphanaJsonConstant.PROTECT_DATABASE: '',
                                                      SaphanaJsonConstant.SYSTEM_DB_USER: self.system_db_user,
                                                      SaphanaJsonConstant.SYSTEMDB_AUTH_TYPE: self.systemdb_auth_type,
                                                      SaphanaJsonConstant.PROTECTDB_AUTH_TYPE: ''
                                                      },
                                                     pid)

    def list_application_v2(self):
        log.info(f"list_application_v2 start, pid={self.pid}.")
        query_type = self.file_content['condition']['conditions'].get('queryType', '')
        response = ListAppV2Response()
        if query_type == ListAppQueryConstant.SYSTEM_DB or query_type == ListAppQueryConstant.NOT_SYSTEM_DB:
            response.resource_list.append(self.query_database_list(query_type))
        output_result_file(self.pid, response.dict(by_alias=True))

    def query_database_list(self, query_type):
        """
        注册时，查询可选择的数据库
        :return:
        """
        resource = Resource()
        database_names = []
        if query_type == ListAppQueryConstant.SYSTEM_DB:
            database_names = [SaphanaConst.SYSTEM_DB]
        elif query_type == ListAppQueryConstant.NOT_SYSTEM_DB:
            if int(self.systemdb_auth_type) == AuthType.OTHER.value:
                db_pwd_env = (
                    f"{SaphanaJsonConstant.APPLICATIONS}_{SaphanaJsonConstant.AUTH}"
                    f"_{SaphanaJsonConstant.EXTEND_INFO}_{SaphanaJsonConstant.KEY_INFO}"
                    f"_{self.pid}")
            else:
                db_pwd_env = (
                    f"{SaphanaJsonConstant.APPLICATIONS}_{SaphanaJsonConstant.AUTH}_{SaphanaJsonConstant.AUTH_PWD}"
                    f"_{self.pid}")
            query_cmd = "SELECT DATABASE_NAME FROM M_DATABASES;"
            ret, output = self._saphana_cluster.execute_query_in_db(SaphanaConst.SYSTEM_DB, self.system_db_user,
                                                                    db_pwd_env, query_cmd)
            if not ret:
                log.error(f"Fail to query databases for register.")
                return resource
            lines = [
                line.strip().strip('\"')
                for line in output.split('\r', 1)[1].strip().split('\r')
                if line.strip().strip('\"') != SaphanaConst.SYSTEM_DB
            ]
            database_names = lines[1:-1]
        resource.extend_info = dict()
        resource.extend_info["db"] = json.dumps(database_names)
        return resource

    def _init_db_param(self, pid):
        self.file_content = ParamFileUtil.parse_param_file(pid)
        self.systemdb_auth_type = get_env_variable(
            (f"{SaphanaJsonConstant.APPLICATIONS}_{SaphanaJsonConstant.AUTH}_{SaphanaJsonConstant.AUTH_TYPE}"
             f"_{self.pid}"))
        self.sid = self.file_content['applications'][0]['extendInfo'].get('systemId', '')
        self.system_db_port = self.file_content['applications'][0]['extendInfo'].get('systemDbPort', '')
        self.system_db_user = get_env_variable(
            (f"{SaphanaJsonConstant.APPLICATIONS}_{SaphanaJsonConstant.AUTH}_{SaphanaJsonConstant.AUTH_KEY}"
             f"_{self.pid}"))
